package com.jackrain.nea.fc.dl.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.ViewDLTranToF4QueryCmd;
import com.jackrain.nea.fc.dl.mapper.ViewDLTranToF4Mapper;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 调拨单（调拨出库单）
 *
 * @author wuwenxue
 * @date 2018/05/22
 **/
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class ViewDLTranToF4QueryCmdImpl extends CommandAdapter implements ViewDLTranToF4QueryCmd {
    private final static FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd");

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {
        ValueHolder vh = new ValueHolder();
        ViewDLTranToF4Mapper viewDLTranToF4Mapper = ApplicationContextHandle.getBean(
                ViewDLTranToF4Mapper.class);
        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(
                map.get("param"), "yyyy-MM-dd HH:mm:ss"), Feature.OrderedField);
        log.info("ViewDLTranToF4QueryCmdImpl--param-->{}",param);

        if (null == param || (!param.containsKey("IDS")) || param.getJSONArray("IDS").size() <= 0) {
            throw new NDSException("参数格式错误！");
        }

        Object[] ids = param.getJSONArray("IDS").toArray();
        String action = param.getString("action");
        JSONArray jsonArray = new JSONArray();

        if ("sendout".equals(action) || "submit".equals(action)) {
            List<HashMap> list = null;
            if ("sendout".equals(action)) {
                list = viewDLTranToF4Mapper.selTranData(ids, null, null, 2, null);
            } else if ("submit".equals(action)) {
                list = viewDLTranToF4Mapper.selTranData(ids, 2, null, null, null);
            }

            for (HashMap hashMap : list) {
                //加补类型
                Long addTypeId = TypeUtils.castToLong(hashMap.get("ADD_TYPE_ID"));
                if (null != addTypeId) {
                    String ecdoe = viewDLTranToF4Mapper.selAddType(addTypeId);
                    hashMap.put("ADD_TYPE", ecdoe);
                }

                Long id = TypeUtils.castToLong(hashMap.get("ID"));
                String billNo = TypeUtils.castToString(hashMap.get("BILL_NO"));
                hashMap.put("BILL_TYPE", "tran");

                Date billDate = TypeUtils.castToDate(hashMap.get("BILL_DATE"));
                String formatBillDate = DATE_FORMAT.format(billDate);

                hashMap.put("BILL_DATE", formatBillDate);

                List<HashMap> itemList = viewDLTranToF4Mapper.selTranItemData(id);
                JSONArray itemArray = new JSONArray();
                for (HashMap itemH : itemList) {
                    itemH.put("BILL_NO", billNo);

                    //出库数量
                    BigDecimal qtyOut = TypeUtils.castToBigDecimal(itemH.get("QTY_OUT"));
                    //入库数量
                    BigDecimal qtyIn = TypeUtils.castToBigDecimal(itemH.get("QTY_IN"));
                    //吊牌价
                    BigDecimal priceList = TypeUtils.castToBigDecimal(itemH.get("PRICE_LIST"));
                    //成本价
                    BigDecimal priceCost = TypeUtils.castToBigDecimal(itemH.get("PRICE_COST"));
                    //是否缓冲补货
                    String isBfSupply = TypeUtils.castToString(itemH.get("IS_BF_SUPPLY"));
                    //调拨数量
                    BigDecimal qtyBill = TypeUtils.castToBigDecimal(itemH.get("QTY_BILL"));
                    //结算价
                    BigDecimal settlementPrice = TypeUtils.castToBigDecimal(itemH.get("SETTLEMENT_PRICE"));
                    //结算金额
                    BigDecimal settlementAmt = TypeUtils.castToBigDecimal(itemH.get("SETTLEMENT_AMT"));

                    if (null != itemH.get("PRICE_LIST")) {
                        if (null != itemH.get("QTY_BILL")) {
                            //调拨金额
                            itemH.put("AMT_LIST", qtyBill.multiply(priceList));
                        }
                        if (null != itemH.get("QTY_OUT")) {
                            //出库金额
                            itemH.put("AMT_LIST_OUT", qtyOut.multiply(priceList));
                        }
                        if (null != itemH.get("QTY_IN")) {
                            //入库金额
                            itemH.put("AMT_LIST_IN", qtyIn.multiply(priceList));
                        }
                    }

                    if (null != itemH.get("PRICE_COST")) {
                        if (null != itemH.get("QTY_OUT")) {
                            //调拨出成本金额
                            itemH.put("AMT_OUT_COST", qtyOut.multiply(priceCost));
                        }
                        if (null != itemH.get("QTY_IN")) {
                            //调拨入成本金额
                            itemH.put("AMT_IN_COST", qtyIn.multiply(priceCost));
                        }
                    }

                    if (null != settlementPrice) {
                        itemH.put("SETTLEMENT_PRICE", settlementPrice);
                    } else {
                        itemH.put("SETTLEMENT_PRICE", 0);
                    }

                    if (null != settlementAmt) {
                        itemH.put("SETTLEMENT_AMT", settlementAmt);
                    } else {
                        itemH.put("SETTLEMENT_AMT", 0);
                    }



                    if ("Y".equals(isBfSupply)) {
                        itemH.put("BF_SUPPLY", 1);
                    } else if ("N".equals(isBfSupply)) {
                        itemH.put("BF_SUPPLY", 0);
                    } else {
                        log.debug("BF_SUPPLY==" + isBfSupply);
                    }

                    JSONObject itemjs = new JSONObject(itemH);
                    itemArray.add(itemjs);
                }

                JSONObject js = new JSONObject(hashMap);
                js.put("DL_B_TRAN_ITEM_SKU", itemArray);
                JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(js,
                        "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                jsonArray.add(param1);

            }
        } else if ("unsubmit".equals(action)) {
            //取消提交
            List<HashMap> list = viewDLTranToF4Mapper.selTranData(ids, 1, null, null, null);

            for (HashMap hashMap : list) {
                JSONObject terJson = new JSONObject();
                terJson.put("BILL_TYPE", "TRAN_OUT");
                terJson.put("BILL_NO", hashMap.get("BILL_NO"));
                terJson.put("STATUS_TYPE", "UNCHK");
                terJson.put("OPR_ECODE", hashMap.get("MODIFIERNAME"));
                terJson.put("OPR_ENAME", hashMap.get("MODIFIERENAME"));
                terJson.put("OPR_DATE", hashMap.get("CANCELER_TIME"));

                JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(terJson,
                        "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                jsonArray.add(param1);
            }
        } else if ("void".equals(action)) {
            //作废
            List<HashMap> list = viewDLTranToF4Mapper.selTranData(ids, null, "N", null, null);
            for (HashMap hashMap : list) {
                JSONObject terJson = new JSONObject();

                terJson.put("BILL_TYPE", "TRAN_OUT");
                terJson.put("BILL_NO", hashMap.get("BILL_NO"));
                terJson.put("STATUS_TYPE", "DEL");
                terJson.put("OPR_ECODE", hashMap.get("MODIFIERNAME"));
                terJson.put("OPR_ENAME", hashMap.get("MODIFIERENAME"));
                terJson.put("OPR_DATE", hashMap.get("DEL_TIME"));

                JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(terJson,
                        "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                jsonArray.add(param1);
            }
        } else if ("change_arrival_time".equals(action)) {
            //修改调拨到货日期
            List<HashMap> list = viewDLTranToF4Mapper.selTranData(ids, null, null, null, null);
            for (HashMap hashMap : list) {

                String isPick = TypeUtils.castToString(hashMap.get("IS_PICK"));
                if ("N".equals(isPick)) {
                    JSONObject terJson = arriavlTimeData(hashMap);
                    JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(terJson,
                            "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                    jsonArray.add(param1);
                } else if ("Y".equals(isPick)) {
                    Long id = TypeUtils.castToLong(hashMap.get("ID"));
                    List<Long> sourceIdList = viewDLTranToF4Mapper.selTranSourceData(id);
                    if (null != sourceIdList && sourceIdList.size() > 0) {
                        Object[] pickids = sourceIdList.toArray();
                        List<HashMap> picklist = viewDLTranToF4Mapper.selTranData(pickids, null, null, null, null);
                        for (HashMap pickMap : picklist) {
                            JSONObject terJson = arriavlTimeData(pickMap);
                            JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(terJson,
                                    "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                            jsonArray.add(param1);
                        }
                    }
                }
            }
        } else if ("accept".equals(action)) {
            //验收
            List<HashMap> list = viewDLTranToF4Mapper.selTranData(ids, null, null, null, 2);


            for (HashMap hashMap : list) {

                if (!"Y".equals(hashMap.get("IS_PICK"))) {

                    JSONObject terJson = new JSONObject();

                    terJson.put("BILL_TYPE", "TRAN_IN");
                    terJson.put("BILL_NO", hashMap.get("BILL_NO"));
                    terJson.put("STATUS_TYPE", "ACCEPT");
                    terJson.put("OPR_ECODE", hashMap.get("MODIFIERNAME"));
                    terJson.put("OPR_ENAME", hashMap.get("MODIFIERENAME"));
                    terJson.put("OPR_DATE", hashMap.get("ACCEPT_TIME"));
                    terJson.put("USERDEFINE1", hashMap.get("ARRIVAL_TIME_APPLY"));
                    terJson.put("USERDEFINE2", hashMap.get("STORE_DATE_IN"));

                    Long id = TypeUtils.castToLong(hashMap.get("ID"));
                    List<HashMap> itemList = viewDLTranToF4Mapper.selTranItemData(id);
                    JSONArray itemArray = new JSONArray();
                    for (HashMap itemH : itemList) {
                        JSONObject itemJson = new JSONObject();
                        itemJson.put("SKU", itemH.get("PS_C_SKU_ECODE"));
                        itemJson.put("QTY", itemH.get("QTY_IN"));
                        itemArray.add(itemJson);
                    }
                    terJson.put("DL_T_BILL_STATUS_CHANGE_ITEM", itemArray);

                    JSONObject param1 = JSON.parseObject(JSON.toJSONStringWithDateFormat(terJson,
                            "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
                    jsonArray.add(param1);
                }
            }
        }

        vh.put("data", jsonArray);
        return vh;
    }

    private JSONObject arriavlTimeData(HashMap hashMap) {
        JSONObject terJson = new JSONObject();

        terJson.put("BILL_TYPE", "TRAN_IN");
        terJson.put("BILL_NO", hashMap.get("BILL_NO"));
        terJson.put("STATUS_TYPE", "CHANG_ARRIVAL_TIME");
        terJson.put("USERDEFINE1", hashMap.get("ARRIVAL_TIME_APPLY"));
        terJson.put("USERDEFINE2", hashMap.get("BILL_DATE"));
        terJson.put("USERDEFINE3", hashMap.get("SP_STOCK_DATE"));
        terJson.put("OPR_ECODE", hashMap.get("MODIFIERNAME"));
        terJson.put("OPR_ENAME", hashMap.get("MODIFIERENAME"));
        terJson.put("OPR_DATE", hashMap.get("MODIFIEDDATE"));

        return terJson;
    }

}
